<template>
  <div class="p-4 add-website" style="background-color: #fff" v-if="props.isAddWebsite">
    <el-button @click="close" class="mb-4">
      <Icon icon="tabler:arrow-back-up" />
      返回
    </el-button>
    <div class="add-website-form p-5 w-80%">
      <div class="website-form-con">
        <el-form
          label-width="100px"
          :model="form"
          :rules="rules"
          ref="websiteFormRef"
          class="website-form"
          label-position="left"
        >
          <h2 class="mb-4">
            <span class="title inline-block bg-[#3721FF] rounded-[50%]"></span>
            网站设置
          </h2>
          <div class="pl-20">
            <el-form-item label="网站logo" prop="webLogo">
              <div
                class="w-100px h-100px border-6 border-solid border-[#F7F7FB] rounded-2xl flex flex-col justify-center items-center"
              >
                <UploadImg v-model="form.webLogo" height="100px" width="100px" class="min-w-80px">
                  <template #empty>
                    <!-- 空但占位 -->
                    <span style="display: none"></span>
                  </template>
                  <template #button>
                    <Icon icon="mi:cloud-upload" :size="20" class="text-[#3721FF]" />
                    <span class="text-[#3721FF]">上传图片</span>
                  </template>
                </UploadImg>
              </div>
              <div class="flex flex-col mt-2 ml-6 text-gray-400 text-12px">
                <span>·尺寸建议1 : 1</span>
                <span>·图片大小不可超过5XM</span>
              </div>
            </el-form-item>
            <el-form-item label="网站图标" prop="webIcon">
              <div
                class="w-100px h-100px border-6 border-solid border-[#F7F7FB] rounded-2xl flex flex-col justify-center items-center"
              >
                <UploadImg v-model="form.webIcon" height="100px" width="100px" class="min-w-80px">
                  <template #empty>
                    <!-- 空但占位 -->
                    <span style="display: none"></span>
                  </template>
                  <template #button>
                    <Icon icon="mi:cloud-upload" :size="20" class="text-[#3721FF]" />
                    <span class="text-[#3721FF]">上传图片</span>
                  </template>
                </UploadImg>
              </div>
            </el-form-item>
            <el-form-item label="网站名称" prop="webName">
              <el-input placeholder="请输入" v-model="form.webName" />
            </el-form-item>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="网站域名" prop="domain">
                  <el-input placeholder="无需http：//或https://" v-model="form.domain" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="地区" prop="areaId">
                  <el-select placeholder="请选择地区" v-model="form.areaId" @change="changeArea">
                    <el-option
                      v-for="item in salesRegion"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="创建部门" prop="deptId">
                  <el-tree-select
                    v-model="form.deptId"
                    :data="proDeptList"
                    :props="defaultProps"
                    check-strictly
                    node-key="id"
                    placeholder="请选择部门"
                    @focus="treeSelectFocus"
                    @change="treeSelectChange"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="语言" prop="language">
                  <el-select
                    placeholder="请选择语言"
                    v-model="form.language"
                    @focus="focusLanguage"
                  >
                    <el-option
                      v-for="item in languageList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="创建者" prop="userId">
                  <el-select placeholder="请选择" v-model="form.userId" @focus="focusUser">
                    <el-option
                      v-for="item in listByDeptList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="14">
                <el-form-item label="站点权限" prop="dataScope">
                  <el-radio-group v-model="form.dataScope">
                    <el-radio label="0">仅自己</el-radio>
                    <el-radio label="1">所有</el-radio>
                    <el-radio label="3">指定人员</el-radio>
                  </el-radio-group>
                  <div class="block">
                    <div v-if="form.dataScope == 3" class="flex">
                      <el-button type="primary" color="#3721FF" @click="handleSelectUser">
                        选择人
                      </el-button>
                      <div class="ml-2">
                        <!-- 最大只显示三个名字，多的后+几个人 -->
                        <template v-for="(item, index) in userList" :key="index">
                          <el-button type="primary" plain color="#3721FF" v-if="index < 3">
                            <span>{{ item.nickName }}</span>
                            <Icon
                              icon="material-symbols-light:cancel"
                              class="ml-2 text-[#999]"
                              @click.stop="handleRemoveUser(index)"
                            />
                          </el-button>
                        </template>
                        <span class="ml-2 text-[#3721FF" v-if="userList?.length > 3">
                          ... {{ userList?.length - 3 }}人</span
                        >
                      </div>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="站点类型" prop="type" class="site-type">
              <el-radio-group v-model="form.type">
                <el-radio label="1">单页站</el-radio>
                <el-radio label="2">独立站</el-radio>
              </el-radio-group>
              <div class="mt-2 text-gray-400 text-12px"
                >注：独立站目前仅适配繁体中文，英语及日语</div
              >
            </el-form-item>
          </div>

          <h2 class="mb-4">
            <span class="title inline-block bg-[#3721FF] rounded-[50%] w-3 h-3"></span>
            网站设置
          </h2>
          <div class="pl-20">
            <row>
              <el-col :span="18">
                <el-form-item label="模板选择" prop="templateId">
                  <!-- <el-input placeholder="请输入" /> -->
                  <el-button
                    color="#3721FF"
                    type="primary"
                    class="mb-4px"
                    @click="handleSelectTemplate"
                  >
                    <Icon icon="ant-design:plus-outlined" />
                    请选择
                  </el-button>
                  <div v-if="selectedTemplateResMap">
                    <div class="flex flex-col items-center ml-6">
                      <!-- <img
                        class="w-50px h-50px rounded-6px"
                        :src="selectedTemplateResMap.previewPicUrls"
                        alt=""
                      /> -->
                      <el-button plain color="#3721FF" class="text-[12px] text-#1A2029">{{
                        selectedTemplateResMap.name
                      }}</el-button>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </row>
            <el-form-item label="轮播图" prop="carousel">
              <UploadImgs v-model="carouselList" height="100px" width="100px" class="min-w-80px">
                <template #empty>
                  <!-- 空但占位 -->
                  <span style="display: none"></span>
                </template>
                <template #button>
                  <div
                    class="w-100px h-100px border-6 border-solid border-[#F7F7FB] rounded-2xl flex flex-col justify-center items-center"
                  >
                    <Icon icon="mi:cloud-upload" :size="20" class="text-[#3721FF]" />
                    <span class="text-[#3721FF]">上传图片</span>
                  </div>
                </template>
              </UploadImgs>
            </el-form-item>
            <row>
              <el-col :span="12">
                <el-form-item label="服务政策" prop="servicePolicyId">
                  <el-select v-model="form.servicePolicyId">
                    <el-option
                      v-for="item in policySimpleList"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </row>
            <el-form-item label="联系我们">
              <el-input
                type="textarea"
                placeholder="请输入"
                :autosize="{ minRows: 8, maxRows: 10 }"
                v-model="form.contactUs"
              />
            </el-form-item>
            <row>
              <el-col :span="14">
                <el-form-item label="FB公共主页">
                  <el-input placeholder="请输入" v-model="form.fbIndex" />
                </el-form-item>
              </el-col>
            </row>
            <el-form-item
              label="商品详情页是否用综合站风格"
              label-width="130px"
              class="site-type"
              prop="name"
            >
              <el-switch
                v-model="form.isIntegratedStation"
                :active-text="form.isIntegratedStation == '0' ? '开启' : '关闭'"
                :active-value="0"
                :inactive-value="1"
              />
              <div class="mt-2 text-gray-400 text-12px"
                >开启后，所有商品落地页将共用站点的模板风格</div
              >
            </el-form-item>
            <el-form-item class="mt-4 el-btn">
              <el-button @click="close">取消</el-button>
              <el-button type="primary" color="#3721FF" @click="submitForm(websiteFormRef)">
                提交
              </el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
  </div>
  <SelectUsers ref="selectUserRef" @select-user="updateSelectUser" :userList="userList" />
  <SelectTemplate
    ref="selectTemplateRef"
    :showDot="true"
    template-type="1"
    width="60%"
    title="选择模板"
    @update:select-template="updateSelectTemplate"
    @selected-template-res="selectedTemplateRes"
    :form-data="form"
  />
</template>


<script setup lang="ts">
import { getGlobeState, getGlobeStateByIdList } from '@/api/publicInterf/index.ts'
import { defaultProps, handleTree } from '@/utils/tree'
import SelectUsers from '@/components/SelectUser/index.vue'
// import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict' //获取字典
// const loadingPageFormType = getStrDictOptions(DICT_TYPE.PRODUCT_FORM_TYPE)
import { WebSiteVO, WebSiteApi } from '@/api/website/website/index'
import * as DeptApi from '@/api/system/dept'
import { ProductApi } from '@/api/product/addProduct'
import SelectTemplate from '@/views/mall/product/product/addProduct/selectTemplate/index.vue'
import { id } from 'element-plus/es/locale'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { deepCopy,throttle } from '@/utils'

const props = defineProps({
  isAddWebsite: {
    type: Boolean,
    default: false
  },
  selectedId: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['close', 'refresh'])
const carouselList = ref([])
const initialForm = {
  id: '', // 网站id
  webLogo: '', // 网站logo
  webIcon: '', // 网站图标
  webName: '', // 网站名称
  domain: '', // 网站域名
  area: '', // 地区
  areaId: '', // 地区id
  deptId: '', // 部门id
  userId: '', // 用户id
  language: '', // 语言
  dataScope: '1', // 数据范围
  dataScopeUserIds: [], // 数据范围用户id
  type: '1', // 站点类型
  templateId: '', // 模板id
  carousel: [], // 轮播图
  servicePolicyId: '', // 服务政策id
  contactUs: '', // 联系我们
  fbIndex: '', // FB公共主页
  isIntegratedStation: '1' // 商品详情页是否用综合站风格
}
const selectUserRef = ref()
const form = ref<WebSiteVO>({ ...initialForm })
const proDeptList = ref()
const policySimpleList = ref([]) //底部政策列表
const listByDeptList = ref([]) //user列表
const languageList = ref([]) //语言
const userInfo = ref()
const userList = ref([])
const selectTemplateRef = ref()

const websiteFormRef = ref()
const rules = {
  webLogo: [{ required: true, message: '请上传网站logo', trigger: 'blur' }],
  // webIcon: [{ required: true, message: '请上传网站图标', trigger: 'blur' }],
  templateId: [{ required: true, message: '请选择模板', trigger: 'change' }],
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  webName: [{ required: true, message: '请输入网站名称', trigger: 'blur' }],
  domain: [{ required: true, message: '请输入网站域名', trigger: 'blur' }],
  carousel: [{ required: true, message: '请上传轮播图', trigger: 'blur' }],
  areaId: [{ required: true, message: '请选择地区', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  language: [{ required: true, message: '请选择语言', trigger: 'change' }]
}

const selectedTemplateResMap = ref()
const selectedTemplateRes = (val) => {
  selectedTemplateResMap.value = val
}
// 点击编辑回填数据回显
const getWebsiteInfo = async () => {
  WebSiteApi.getWebSite(props.selectedId).then(async (res) => {
    form.value = res
    form.value.area = res.area
    form.value.areaId = res.areaId
    form.value.dataScope = res?.dataScope?.toString()
    form.value.type = res?.type?.toString()
    form.value.carousel = res?.carousel?.split(',')
    // form.value.servicePolicyId = res.servicePolicyId?.toString()
    await handleGetUserList(form.value.deptId ? form.value.deptId : userInfo.value?.deptId)
    selectedTemplateResMap.value = templateList.value?.find((item) => item.id == res.templateId)
    carouselList.value = res.carousel
    if (res?.userList) {
      userList.value = res.userList.map((item) => ({
        userId: item.id,
        nickName: item.nickname
      }))
    }
    // 确保 userInfo 已初始化
    if (!userInfo.value) {
      const { wsCache } = useCache()
      userInfo.value = wsCache.get(CACHE_KEY.USER)?.user || {}
    }
    if (form.value?.deptId == null && userInfo.value?.deptId) {
      form.value.deptId = userInfo.value.deptId
    }
    if (form.value?.userId == null && userInfo.value?.id) {
      form.value.userId = userInfo.value.id
    }
    console.log(form.value.deptId, 'form.value')
    console.log(form.value.userId, 'form.value')
  })
}
// 获取底部政策列表
const handlePolicySimpleList = async () => {
  await ProductApi.policySimpleList().then((res) => {
    policySimpleList.value = res.map((item) => ({
      label: item.name,
      value: item.id
    }))
  })
}
// 获取传递模板
const updateSelectTemplate = (val) => {
  form.value.templateId = val
}
const handleSelectTemplate = (val) => {
  selectTemplateRef.value?.show(val)
}
const handleSelectUser = () => {
  selectUserRef.value?.open()
}
const handleRemoveUser = (index) => {
  userList.value.splice(index, 1)
  // form.value.dataScopeUserIds.splice(index, 1)
  // 判断dataScopeUserIds数组里面的id是否在userList.value里面，如果没有则删除
  form.value.dataScopeUserIds = form.value.dataScopeUserIds.filter((item) => {
    return userList.value.some((item1) => item1.userId == item)
  })
}
const updateSelectUser = (data) => {
  form.value.dataScopeUserIds =
    form.value.dataScopeUserIds == undefined ? [] : form.value.dataScopeUserIds
  userList.value = data.map((item) => ({
    userId: item.id,
    nickName: item.name
  }))
  form.value.dataScopeUserIds.push(...data.map((item) => item.id)) // 添加到表单中
}
const open = () => {}
//
const focusLanguage = () => {
  if (!form.value.areaId) {
    ElMessage.warning('请先选择地区')
    return
  }
}
const focusUser = () => {
  if (!form.value.deptId) {
    ElMessage.warning('请先选择部门')
    return
  }
}
// 获取部门列表
const getDeptList = async () => {
  form.value.userId = ''
  try {
    proDeptList.value = handleTree(await DeptApi.getSimpleDeptList())
  } catch (error) {
    console.error('获取部门列表失败:', error)
  }
}
//
const changeArea = () => {
  form.value.language = ''
  salesRegion.value.forEach((item) => {
    if (item.value == form.value.areaId) {
      form.value.area = item.label
      form.value.areaId = item.value
    }
  })
  handleGetGlobeStateByIdList()
}
// 地区
const salesRegion = ref([])
const handleGetGlobeState = async () => {
  try {
    const res = await getGlobeState()
    salesRegion.value = res.map((item) => ({
      label: item.stateName,
      value: item.id
    }))
  } catch (error) {
    console.error('获取全局状态失败:', error)
  }
}
const treeSelectFocus = async () => {
  await getDeptList()
}
//获取部门列表
const treeSelectChange = async (val) => {
  await handleGetUserList(val)
}
// 根据部门ID获取用户下拉列表
const handleGetUserList = async (id) => {
  await ProductApi.listByDept({ deptId: id }).then((res) => {
    listByDeptList.value = res.map((item) => ({
      label: item.nickname,
      value: item.id
    }))
  })
}
// 语言
const handleGetGlobeStateByIdList = async () => {
  try {
    const res = await getGlobeStateByIdList({ id: form.value.areaId })
    languageList.value = res.map((item) => ({
      label: item,
      value: item
    }))
  } catch (error) {
    console.error('获取全局状态失败:', error)
  }
}
const submitForm = throttle(() => {
    form.value.carousel =
      carouselList.value && carouselList.value.length > 0 ? carouselList.value.join(',') : []
    websiteFormRef.value.validate((valid) => {
      if (valid) {
        // 提交表单逻辑
        if (form.value?.id) {
          delete form.value.userList
          WebSiteApi.updateWebSite(form.value).then((res) => {
            ElMessage.success('提交成功')
            // 重置表单
            resetForm()
            close()
            // 刷新父组件
            emit('refresh')
          })
        } else {
          WebSiteApi.createWebSite(form.value).then((res) => {
            ElMessage.success('提交成功')
            // 重置表单
            resetForm()
            close()
            // 刷新父组件
            emit('refresh')
          })
        }
      } else {
        console.error('表单验证失败')
        return false
      }
    })
  },1000)

// 重置
const resetForm = () => {
  // 重置表单
  websiteFormRef.value.resetFields()
}
// 获取模板列表
const templateList = ref([])
const getTemplateList = async () => {
  ProductApi.templatePage().then((res) => {
    templateList.value = res.list
  })
}
const close = () => {
  emit('close')
}
onMounted(async () => {
  const { wsCache } = useCache()
  let userInfos = wsCache.get(CACHE_KEY.USER)
  userInfo.value = userInfos.user
  console.log('userInfo.value6666', userInfo.value)

  handlePolicySimpleList()
  handleGetGlobeState()
  getTemplateList()
  await getDeptList()
  if (props.selectedId) {
    getWebsiteInfo()
  } else {
    resetForm()
  }
})
// 抛出resetForm
defineExpose({
  resetForm
})
</script>
<style lang="scss" scoped>
:deep(.site-type .el-form-item__content) {
  display: block;
}
.el-btn {
  .el-button {
    border-radius: 10px;
    padding: 20px 30px;
  }
  :deep(.el-form-item__content) {
    display: block;
    text-align: center;
  }
}
.title {
  width: 18px;
  height: 18px;
  background: #3721ff;
  box-shadow: 0px 0px 6px 1px rgba(55, 33, 255, 0.19);
  border: 3px solid #ffffff;
}
</style>
